package com.company.cloud.sdk.weixin.mp;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.company.cloud.sdk.weixin.common.constant.WxErrorEnum;
import com.company.cloud.sdk.weixin.common.exception.WxException;
import com.company.cloud.sdk.weixin.common.model.BaseRespModel;
import com.company.cloud.sdk.weixin.mp.enums.WxMpApiType;
import com.company.cloud.sdk.weixin.mp.enums.WxMpDomain;
import com.company.cloud.sdk.weixin.mp.model.*;

import java.util.Map;

/**微信公众号API*/
public class WxMpApi {

    public static String getReqUrl(WxMpApiType wxMpApiType){
        return getReqUrl(wxMpApiType,null);
    }

    public static String getReqUrl(WxMpApiType wxMpApiType, WxMpDomain wxMpDomain){
        if(wxMpDomain==null){
            wxMpDomain=WxMpDomain.CHINA;
        }
        return  wxMpDomain.getType().concat(wxMpApiType.getType());
    }

    /**
     * 基础access_token:access_token (公众号和小程序均可以使用AppID和AppSecret调用本接口来获取access_token)
     * */
    public static String accessToken(Map<String, Object> params) {
        try {
            String url=getReqUrl(WxMpApiType.Access_Token);
            String httpResp= HttpUtil.get(url,params);
            return  httpResp;
        }catch (Exception e){
            throw new WxException(WxErrorEnum.WX_Http_ERROR.getCode(),e.getMessage());
        }
    }

    /**
     * 基础access_token:access_token (公众号和小程序均可以使用AppID和AppSecret调用本接口来获取access_token)
     * */
    public static AccessTokenResp accessToken(AccessTokenModel entity){
        Map<String, Object> params =  BeanUtil.beanToMap(entity,false,true);
        String result= WxMpApi.accessToken(params);
        if(StrUtil.isEmpty(result)){
            throw new WxException(WxErrorEnum.WX_Http_ERROR);
        }
        Map<String,Object> resultMap= JSON.parseObject(result, Map.class);
        AccessTokenResp data= BeanUtil.fillBeanWithMapIgnoreCase(resultMap,new AccessTokenResp(),false);
        if(data.getErrcode()!=null && data.getErrcode()!=0){
            throw new WxException(data.getErrcode(),data.getErrmsg());
        }
        return data;
    }

    /**
     * jsapi_ticket
     * https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html#62
     * */
    public static String jsapiTicket(Map<String, Object> params) {
        try {
            String url=getReqUrl(WxMpApiType.Jsapi_Ticket);
            String httpResp= HttpUtil.get(url,params);
            return  httpResp;
        }catch (Exception e){
            throw new WxException(WxErrorEnum.WX_Http_ERROR.getCode(),e.getMessage());
        }
    }

    /**
     * jsapi_ticket
     * https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html#62
     * */
    public static  JsapiTicketResp jsapiTicket(JsapiTicketModel entity){
        Map<String, Object> params =  BeanUtil.beanToMap(entity,false,true);
        String result= WxMpApi.jsapiTicket(params);
        if(StrUtil.isEmpty(result)){
            throw new WxException(WxErrorEnum.WX_Http_ERROR);
        }
        Map<String,Object> resultMap= JSON.parseObject(result, Map.class);
        JsapiTicketResp data= BeanUtil.fillBeanWithMapIgnoreCase(resultMap,new JsapiTicketResp(),false);
        if(data.getErrcode()!=null && data.getErrcode()!=0){
            throw new WxException(data.getErrcode(),data.getErrmsg());
        }
        return data;
    }

    /**
     *页面access_token:通过code换取网页授权access_token
     * */
    public static String code2Ticket(Map<String, Object> params) {
        try {
            String url=getReqUrl(WxMpApiType.Code2AccessToken);
            String httpResp= HttpUtil.get(url,params);
            return  httpResp;
        }catch (Exception e){
            throw new WxException(WxErrorEnum.WX_Http_ERROR.getCode(),e.getMessage());
        }
    }

    /**
     *页面access_token:通过code换取网页授权access_token
     * */
    public static Code2AccessTokenResp code2Ticket(Code2AccessTokenModel entity){
        Map<String, Object> params =  BeanUtil.beanToMap(entity,false,true);
        String result= WxMpApi.code2Ticket(params);
        if(StrUtil.isEmpty(result)){
            throw new WxException(WxErrorEnum.WX_Http_ERROR);
        }
        Map<String,Object> resultMap= JSON.parseObject(result, Map.class);
        Code2AccessTokenResp data= BeanUtil.fillBeanWithMapIgnoreCase(resultMap,new Code2AccessTokenResp(),false);
        if(data.getErrcode()!=null && data.getErrcode()!=0){
            throw new WxException(data.getErrcode(),data.getErrmsg());
        }
        return data;
    }

    /**
     * 刷新页面access_token:使用refresh_token进行刷新页面access_token,
     * refresh_token有效期为30天，当refresh_token失效之后，需要用户重新授权
     * */
    public static String token2RefreshToken(Map<String, Object> params) {
        try {
            String url=getReqUrl(WxMpApiType.RefreshToken);
            String httpResp= HttpUtil.get(url,params);
            return  httpResp;
        }catch (Exception e){
            throw new WxException(WxErrorEnum.WX_Http_ERROR.getCode(),e.getMessage());
        }
    }

    /**
     * 刷新页面access_token:使用refresh_token进行刷新页面access_token,
     * refresh_token有效期为30天，当refresh_token失效之后，需要用户重新授权
     * */
    public static RefreshTokenResp token2RefreshToken(RefreshTokenModel entity) {
        Map<String, Object> params =  BeanUtil.beanToMap(entity,false,true);
        String result= WxMpApi.token2RefreshToken(params);
        if(StrUtil.isEmpty(result)){
            throw new WxException(WxErrorEnum.WX_Http_ERROR);
        }
        Map<String,Object> resultMap= JSON.parseObject(result, Map.class);
        RefreshTokenResp data= BeanUtil.fillBeanWithMapIgnoreCase(resultMap,new RefreshTokenResp(),false);
        if(data.getErrcode()!=null && data.getErrcode()!=0){
            throw new WxException(data.getErrcode(),data.getErrmsg());
        }
        return data;
    }

    /**
     * 拉取用户信息(需scope为 snsapi_userinfo)
     * 如果网页授权作用域为snsapi_userinfo，则此时开发者可以通过access_token和openid拉取用户信息了
     * */
    public static String userInfo(Map<String, Object> params) {
        try {
            String url=getReqUrl(WxMpApiType.UserInfo);
            String httpResp= HttpUtil.get(url,params);
            return  httpResp;
        }catch (Exception e){
            throw new WxException(WxErrorEnum.WX_Http_ERROR.getCode(),e.getMessage());
        }
    }

    /**
     * 拉取用户信息(需scope为 snsapi_userinfo)
     * 如果网页授权作用域为snsapi_userinfo，则此时开发者可以通过access_token和openid拉取用户信息了
     * */
    public static MpUserInfoResp userInfo(MpUserInfoModel entity) {
        Map<String, Object> params =  BeanUtil.beanToMap(entity,false,true);
        String result= WxMpApi.userInfo(params);
        if(StrUtil.isEmpty(result)){
            throw new WxException(WxErrorEnum.WX_Http_ERROR);
        }
        Map<String,Object> resultMap= JSON.parseObject(result, Map.class);
        MpUserInfoResp data= BeanUtil.fillBeanWithMapIgnoreCase(resultMap,new MpUserInfoResp(),false);
        if(data.getErrcode()!=null && data.getErrcode()!=0){
            throw new WxException(data.getErrcode(),data.getErrmsg());
        }
        return data;
    }

    /**
     * 页面access_token:检验授权凭证（access_token）是否有效
     * */
    public static String authAccessToken(Map<String, Object> params) {
        try {
            String url=getReqUrl(WxMpApiType.AuthToken);
            String httpResp= HttpUtil.get(url,params);
            return  httpResp;
        }catch (Exception e){
            throw new WxException(WxErrorEnum.WX_Http_ERROR.getCode(),e.getMessage());
        }
    }

    /**
     * 页面access_token:检验授权凭证（access_token）是否有效
     * */
    public static BaseRespModel authAccessToken(AuthTokenModel entity) {
        Map<String, Object> params =  BeanUtil.beanToMap(entity,false,true);
        String result= WxMpApi.authAccessToken(params);
        if(StrUtil.isEmpty(result)){
            throw new WxException(WxErrorEnum.WX_Http_ERROR);
        }
        Map<String,Object> resultMap= JSON.parseObject(result, Map.class);
        BaseRespModel data= BeanUtil.fillBeanWithMapIgnoreCase(resultMap,new BaseRespModel(),false);
        if(data.getErrcode()!=null && data.getErrcode()!=0){
            throw new WxException(data.getErrcode(),data.getErrmsg());
        }
        return data;
    }







    public static void main(String[] args) {
//        AccessTokenModel entity=new AccessTokenModel();
//        entity.setAppid("wxe5bb3017fd108c5d");
//        entity.setSecret("c1d31167a5edc9c66772bea7009ee160");
//        AccessTokenResp data= WxMpApi.accessToken(entity);
//        System.out.println(JSON.toJSONString(data));

//        JsapiTicketModel entity=new JsapiTicketModel();
//        entity.setAccess_token("38_rD1_dt3S7REBgucqyde1L1KynNddTRUiXapeIpttMTbzGHMTOkiMLEFJghE-qevf7SQW5rsakCIja1tT4zeC2TH9Sz5ib3HIoeEGSgiSBhw1LIDsBbn7NV9aAOth0-zMaeLdm9g8arEdzMTVTAViAGABID");
//        JsapiTicketResp data= WxMpApi.jsapiTicket(entity);
//        System.out.println(JSON.toJSONString(data));
    }



//
//    /**
//     * 获取用户基本信息
//     * */
//    public MpUserInfoResp getUserInfo(MpUserInfoModel params){
//        return null;
//    }


}
